<template>
  <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="400px" :title="`${drawerProps.title}分类`">
    <el-form
      ref="ruleFormRef"
      label-width="100px"
      label-suffix=" :"
      :rules="rules"
      :disabled="drawerProps.isView"
      :model="drawerProps.row"
      :hide-required-asterisk="drawerProps.isView"
    >
      <el-form-item label="分类图片" prop="imageUrl">
        <UploadImg v-model:image-url="drawerProps.row!.imageUrl" width="104px" height="104px" :file-size="3">
          <template #empty>
            <el-icon><Avatar /></el-icon>
          </template>
          <template #tip> 图片大小不能超过 3M </template>
        </UploadImg>
      </el-form-item>
      <el-form-item label="分类名称" prop="name">
        <el-input v-model="drawerProps.row!.name" placeholder="请填分类名称" clearable></el-input>
      </el-form-item>
      <el-form-item label="父级分类" prop="parentId">
        <el-tree-select v-model="drawerProps.row!.parentId" :data="categoryList" :render-after-expand="true" />
      </el-form-item>
      <el-form-item label="是否显示" prop="isShow">
        <el-switch v-model="drawerProps.row!.isShow" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="drawerVisible = false"> 取消 </el-button>
      <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit"> 确定 </el-button>
    </template>
  </el-drawer>
</template>

<script setup lang="ts" name="ProductCategoryDrawer">
import { ref, reactive, watch } from "vue";
import { ElMessage, FormInstance } from "element-plus";
import { Product } from "@/api/interface";
import UploadImg from "@/components/Upload/Img.vue";
import { getCategoryDictionary } from "@/api/modules/product";

const rules = reactive({
  name: [{ required: true, message: "请填写分类名称" }]
});

interface DrawerProps {
  title: string;
  isView: boolean;
  row: Partial<Product.ResCategoryList>;
  api?: (params: any) => Promise<any>;
  getTableList?: () => void;
}

const categoryList = ref([]); // 初始化为空数组

interface CategoryData {
  // 这里根据你的实际数据结构定义类型
  // 假设 data.categories.data 是一个数组，包含分类数据
  categories: {
    data: Category[]; // Category 是表示分类数据的类型
  };
}

interface Category {
  // 根据你的分类数据结构定义类型
  // 例如：
  id: number;
  checkArr: string;
  title: string;
  children: string[];
  // ...其他属性
}

interface OriginalCategory {
  checkArr: string;
  children: OriginalCategory[];
  id: number;
  last: boolean;
  parentId: string;
  title: string;
}

interface TransformedCategory {
  value: number;
  label: string;
  children: TransformedCategory[];
}

function transformCategory(original: OriginalCategory): TransformedCategory {
  const transformed: TransformedCategory = {
    value: Number(original.id),
    label: original.title,
    children: []
  };

  if (original.children && original.children.length > 0) {
    transformed.children = original.children.map(child => transformCategory(child));
  }

  return transformed;
}

// 在适当的时机调用网络请求获取分类数据
const fetchCategoryList = async () => {
  try {
    const { data }: { data: CategoryData } = await getCategoryDictionary();
    // 调用网络请求方法获取数据
    // console.log("response", data.categories.data);
    categoryList.value = data.categories.data.map(category => transformCategory(category)); // 假设接口返回的数据在 response.data 中，你需要根据实际情况进行替换
  } catch (error) {
    console.error("Failed to fetch category list:", error);
  }
};

const drawerVisible = ref(false);
const drawerProps = ref<DrawerProps>({
  isView: false,
  title: "",
  row: {}
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
  drawerProps.value = params;
  drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const ruleFormRef = ref<FormInstance>();
const handleSubmit = () => {
  ruleFormRef.value!.validate(async valid => {
    if (!valid) return;
    try {
      await drawerProps.value.api!(drawerProps.value.row);
      ElMessage.success({ message: `${drawerProps.value.title}品牌成功！` });
      drawerProps.value.getTableList!();
      drawerVisible.value = false;
    } catch (error) {
      console.log(error);
    }
  });
};

// 在 drawerVisible 变为 true 时加载分类接口数据
watch(drawerVisible, newVal => {
  if (newVal) {
    fetchCategoryList();
  }
});

defineExpose({
  acceptParams
});
</script>
